<template>
  <div class="app-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="dashboard-cards">
      <el-col :span="6">
        <div class="stat-card blue">
          <div class="stat-title">总配置数</div>
          <div class="stat-value">{{ total }}</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card purple">
          <div class="stat-title">微信支付</div>
          <div class="stat-value">{{ getPayTypeCount('1') }}</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card orange">
          <div class="stat-title">支付宝支付</div>
          <div class="stat-value">{{ getPayTypeCount('2') }}</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card green">
          <div class="stat-title">启用配置</div>
          <div class="stat-value">{{ getActiveCount() }}</div>
        </div>
      </el-col>
    </el-row>

    <!-- 搜索表单 -->
    <div class="search-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
        <el-form-item label="停车场" prop="lotName">
          <el-input 
            v-model="queryParams.lotName" 
            placeholder="请输入停车场名称" 
            clearable 
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="支付类型" prop="payType">
          <el-select 
            v-model="queryParams.payType" 
            placeholder="请选择支付类型" 
            clearable 
            size="small"
          >
            <el-option label="微信支付" value="1" />
            <el-option label="支付宝" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            icon="el-icon-search" 
            size="mini" 
            @click="handleQuery"
          >搜索</el-button>
          <el-button 
            icon="el-icon-refresh" 
            size="mini" 
            @click="resetQuery"
          >重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="action-container">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增配置</el-button>
    </div>

    <!-- 表格部分 -->
    <el-card class="table-card">
      <el-table v-loading="loading" :data="configList" stripe>
        <el-table-column label="停车场" align="center" prop="lotName" />
        <el-table-column label="支付类型" align="center" prop="payType">
          <template slot-scope="scope">
            {{ scope.row.payType === '1' ? '微信支付' : '支付宝' }}
          </template>
        </el-table-column>
        <el-table-column label="商户号" align="center" prop="merchantId" />
        <el-table-column label="优先级" align="center" prop="priority" />
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="0"
              inactive-value="1"
              @change="handleStatusChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加或修改支付配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="停车场" prop="lotId">
          <el-select 
            v-model="form.lotId" 
            placeholder="请选择停车场"
            clearable
          >
            <el-option
              v-for="item in parkingLots"
              :key="item.lotId"
              :label="item.lotName"
              :value="item.lotId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="支付类型" prop="payType">
          <el-select v-model="form.payType" placeholder="请选择支付类型">
            <el-option
              v-for="dict in payTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商户号" prop="merchantId">
          <el-input v-model="form.merchantId" placeholder="请输入商户号" />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number v-model="form.priority" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listConfig, getConfig, addConfig, updateConfig, delConfig, changeConfigStatus } from "@/api/config";
import { parkingApi } from "@/api/parking";

export default {
  name: "ParkingPaymentConfig",
  data() {
    return {
      loading: false,
      showSearch: true,
      total: 0,
      configList: [],
      title: "",
      open: false,
      payTypeOptions: [
        { dictLabel: '微信支付', dictValue: '1' },
        { dictLabel: '支付宝', dictValue: '2' }
      ],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        lotName: undefined,
        payType: undefined
      },
      form: {
        configId: null,
        lotId: undefined,
        payType: '',
        merchantId: '',
        merchantName: '',
        appId: '',
        merchantKey: '',
        priority: 0,
        status: '0'
      },
      rules: {
        lotId: [
          { required: true, message: "请选择停车场", trigger: "change" }
        ],
        payType: [
          { required: true, message: "支付类型不能为空", trigger: "change" }
        ],
        merchantId: [
          { required: true, message: "商户号不能为空", trigger: "blur" }
        ],
        priority: [
          { required: true, message: "优先级不能为空", trigger: "blur" }
        ]
      },
      parkingLots: []
    };
  },
  created() {
    console.log('组件创建，准备获取数据...');  // 添加日志
    this.getList();
  },
  methods: {
    /** 查询支付配置列表 */
    getList() {
      this.loading = true;
      console.log('开始获取数据...');
      
      // 处理查询参数
      const params = {
        ...this.queryParams,
        lotName: this.queryParams.lotName?.trim() || undefined,
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize
      };
      
      console.log('处理后的查询参数:', params);
      
      listConfig(params).then(response => {
        console.log('API响应:', response);
        if (response.code === 200) {
          this.configList = response.data || [];
          this.total = response.total || 0;
          // 获取每个配置项的停车场名称
          this.configList.forEach(item => {
            this.getParkingLotName(item);
          });
        } else {
          this.$message.error(response.msg || '获取数据失败');
        }
      }).catch(error => {
        console.error('获取数据失败:', error);
        this.$message.error('获取数据失败：' + error.message);
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // 确保搜索条件不为空字符串
      if (this.queryParams.lotName === '') {
        this.queryParams.lotName = undefined;
      }
      console.log('执行搜索，参数:', this.queryParams);
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        lotName: undefined,
        payType: undefined
      };
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加支付配置";
      
      // 获取停车场列表
      this.loading = true;
      
      parkingApi.getParkingLotList().then(response => {
        console.log('停车场列表响应:', response);
        
        if (response && response.code === 200 && response.data) {
          // 从嵌套的 data 中获取 rows
          const parkingData = response.data.rows;
          if (Array.isArray(parkingData)) {
            this.parkingLots = parkingData;
            console.log('获取到的停车场列表:', this.parkingLots);
          } else {
            console.error('rows 不是数组:', parkingData);
            this.$message.error('数据格式错误');
          }
        } else {
          console.error('API响应异常:', response);
          this.$message.error(response?.msg || '获取停车场列表失败');
        }
      }).catch(error => {
        console.error('API请求失败:', error);
        this.$message.error('获取停车场列表失败: ' + (error.message || '未知错误'));
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const configId = row.configId;
      
      Promise.all([
        parkingApi.getParkingLotList(),
        getConfig(configId)
      ]).then(([lotResponse, configResponse]) => {
        if (lotResponse.code === 200 && lotResponse.data) {
          const parkingData = lotResponse.data.rows;
          if (Array.isArray(parkingData)) {
            this.parkingLots = parkingData;
          }
        }
        if (configResponse.code === 200) {
          this.form = configResponse.data;
          this.open = true;
          this.title = "修改支付配置";
        }
      }).catch(error => {
        console.error('获取数据失败:', error);
        this.$message.error('获取数据失败');
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 构建提交数据
          const submitData = {
            configId: this.form.configId, // 修改时需要传入ID
            lotId: Number(this.form.lotId),
            payType: this.form.payType,
            merchantId: this.form.merchantId,
            priority: Number(this.form.priority),
            status: this.form.status
          };

          if (this.form.configId) {
            // 修改操作
            updateConfig(submitData).then(response => {
              if (response.code === 200) {
                this.$message.success("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.$message.error(response.msg || "修改失败");
              }
            }).catch(error => {
              console.error('修改失败:', error);
              this.$message.error("修改失败：" + error.message);
            });
          } else {
            // 新增操作
            addConfig(submitData).then(response => {
              if (response.code === 200) {
                this.$message.success("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.$message.error(response.msg || "新增失败");
              }
            }).catch(error => {
              console.error('新增失败:', error);
              this.$message.error("新增失败：" + (error.message || '未知错误'));
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // 打印要删除的数据
      console.log('删除的行数据:', row);
      
      const configId = row.configId;
      if (!configId) {
        this.$message.error('无效的配置ID');
        return;
      }

      this.$confirm('是否确认删除支付配置编号为"' + configId + '"的数据项？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        // 确保 configId 是数字类型
        return delConfig(Number(configId));
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch((err) => {
        console.error('删除操作错误:', err);
        if (err !== 'cancel') {
          this.$message.error("删除失败");
        } else {
          this.$message.info("已取消删除");
        }
      });
    },
    /** 状态修改 */
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      
      // 使用 element-ui 的 MessageBox.confirm 替代 this.$modal
      this.$confirm('确认要"' + text + '""' + row.lotName + '"的支付配置吗？', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return changeConfigStatus(row);
      }).then(() => {
        this.$message.success(text + "成功");
      }).catch((err) => {
        if (err !== 'cancel') {
          this.$message.error("操作失败");
        }
        // 恢复开关状态
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 表单重置
    reset() {
      this.form = {
        configId: undefined,
        lotId: undefined,
        payType: undefined,
        merchantId: '',
        priority: 0,
        status: '0'
      };
      
      if (this.$refs["form"]) {
        this.$refs["form"].resetFields();
      }
    },
    /** 获取停车场名称 */
    getParkingLotName(item) {
      if (item.lotId) {
        parkingApi.getParkingLotInfo(item.lotId).then(response => {
          if (response.data && response.data.lotName) {
            this.$set(item, 'lotName', response.data.lotName);
          }
        }).catch(error => {
          console.error('获取停车场名称失败:', error);
        });
      }
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    // 添加新的统计方法
    getPayTypeCount(type) {
      return this.configList.filter(item => item.payType === type).length;
    },
    getActiveCount() {
      return this.configList.filter(item => item.status === '0').length;
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.dashboard-cards {
  margin-bottom: 20px;
  
  .stat-card {
    padding: 20px;
    border-radius: 10px;
    color: white;
    height: 120px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    
    .stat-title {
      font-size: 16px;
      opacity: 0.9;
    }
    
    .stat-value {
      font-size: 32px;
      font-weight: bold;
    }
    
    &.blue {
      background: linear-gradient(135deg, #1890ff 0%, #36a6ff 100%);
    }
    
    &.purple {
      background: linear-gradient(135deg, #722ed1 0%, #8e44ad 100%);
    }
    
    &.orange {
      background: linear-gradient(135deg, #ff6b00 0%, #ff8c3f 100%);
    }
    
    &.green {
      background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
    }
  }
}

.search-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.05);
}

.action-container {
  margin-bottom: 20px;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.05);
  
  .el-table {
    margin: 10px 0;
  }
}

.el-button {
  border-radius: 4px;
  
  &--primary {
    background: #1890ff;
    border-color: #1890ff;
    
    &:hover, &:focus {
      background: #40a9ff;
      border-color: #40a9ff;
    }
  }
}

.el-input, .el-select {
  .el-input__inner {
    border-radius: 4px;
  }
}

.pagination-container {
  padding: 15px 0;
  text-align: right;
}
</style> 